package com.doubao.hardware.controller;

import com.doubao.hardware.context.UserContext;
import com.doubao.hardware.dto.ApiResponse;
import com.doubao.hardware.entity.HardwareDeviceEntity;
import com.doubao.hardware.mapper.HardwareDeviceMapper;
import com.doubao.hardware.service.DeviceHardwareService;
import com.doubao.hardware.service.impl.DeviceRegistrationServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 硬件设备-智能体关联控制器
 * 提供设备与智能体关联的REST API
 */
@RestController
@RequestMapping("/hardware/ai")
@RequiredArgsConstructor
@Slf4j
public class HardwareSmartDeviceController {

    private final DeviceHardwareService deviceHardwareService;
    private final HardwareDeviceMapper hardwareDeviceMapper;

    /**
     * 配置设备的智能体
     * @param macAddress 设备MAC地址
     * @param requestBody 请求参数，包含smartDeviceId
     * @return 配置结果
     */
    @PostMapping("/configure/{macAddress}")
    public ApiResponse<Map<String, Object>> configureDeviceAI(
            @PathVariable String macAddress,
            @RequestBody Map<String, Long> requestBody) {

        try {
            // 现有代码保持不变
            Long smartDeviceId = requestBody.get("smartDeviceId");
            if (smartDeviceId == null) {
                return ApiResponse.error("智能体ID不能为空");
            }

            // 获取设备信息
            HardwareDeviceEntity device = hardwareDeviceMapper.selectByMacAddress(macAddress);
            if (device == null) {
                return ApiResponse.error(404, "设备不存在，请先注册设备");
            }

            // 检查设备是否已被其他用户绑定
            Long currentUserId = UserContext.getUserId();
            if (device.getUserId() != null && currentUserId != null &&
                    !device.getUserId().equals(currentUserId)) {

                log.warn("设备 {} 已被用户 {} 绑定，当前用户 {} 尝试配置",
                        macAddress, device.getUserId(), currentUserId);

                return ApiResponse.error(403, "设备已被其他用户绑定，无法配置");
            }

            // 检查是否与当前智能体ID相同，如果不同则强制更新
            Long currentSmartDeviceId = deviceHardwareService.getCurrentSmartDeviceId(macAddress);
            boolean forceUpdate = currentSmartDeviceId == null || !currentSmartDeviceId.equals(smartDeviceId);

            // 如果强制更新，先清除缓存
            if (forceUpdate) {
                deviceHardwareService.clearDeviceCache(macAddress);
            }

            boolean result = deviceHardwareService.configureDeviceAI(macAddress, smartDeviceId, forceUpdate);

            if (result) {
                // 成功逻辑
                Map<String, Object> data = new HashMap<>();
                data.put("macAddress", macAddress);
                data.put("smartDeviceId", smartDeviceId);
                data.put("configured", true);
                data.put("deviceId", device.getId());

                device.setSmartDeviceId(smartDeviceId);
                device.setUpdatedAt(LocalDateTime.now());
                hardwareDeviceMapper.updateById(device);

                return ApiResponse.success("设备智能体配置成功", data);
            } else {
                return ApiResponse.error("设备智能体配置失败");
            }
        } catch (Exception e) {
            log.error("配置设备智能体失败", e);

            // 更具体的错误处理
            String errorMessage = e.getMessage();
            if (e instanceof DeviceRegistrationServiceImpl.DeviceAlreadyBoundException) {
                Long boundUserId = ((DeviceRegistrationServiceImpl.DeviceAlreadyBoundException) e).getBoundUserId();
                return ApiResponse.error(403,
                        "设备已被用户ID为 " + (boundUserId != null ? boundUserId : "未知") + " 的用户绑定，请先解绑"
                );
            }

            return ApiResponse.error("配置设备智能体失败: " + errorMessage);
        }
    }

    /**
     * 清除设备的智能体配置
     * @param macAddress 设备MAC地址
     * @return 清除结果
     */
    @PostMapping("/clear/{macAddress}")
    public ApiResponse<Void> clearDeviceAI(@PathVariable String macAddress) {
        try {
            log.info("开始清除设备 {} 的智能体配置", macAddress);

            boolean result = deviceHardwareService.clearDeviceAI(macAddress);

            if (result) {
                return ApiResponse.success("设备智能体配置已清除");
            } else {
                return ApiResponse.error("清除设备智能体配置失败");
            }
        } catch (Exception e) {
            log.error("清除设备智能体配置失败", e);
            return ApiResponse.error("清除设备智能体配置失败: " + e.getMessage());
        }
    }

    /**
     * 获取设备当前配置的智能体
     * @param macAddress 设备MAC地址
     * @return 智能体信息
     */
    @GetMapping("/current/{macAddress}")
    public ApiResponse<Map<String, Object>> getCurrentSmartDevice(@PathVariable String macAddress) {
        try {
            log.info("获取设备 {} 当前配置的智能体", macAddress);

            Long smartDeviceId = deviceHardwareService.getCurrentSmartDeviceId(macAddress);

            Map<String, Object> data = new HashMap<>();
            data.put("macAddress", macAddress);
            data.put("smartDeviceId", smartDeviceId);
            data.put("configured", smartDeviceId != null);

            return ApiResponse.success(data);
        } catch (Exception e) {
            log.error("获取设备当前智能体失败", e);
            return ApiResponse.error("获取设备当前智能体失败: " + e.getMessage());
        }
    }
}